# pragma once

# include <vector>
# include "../ganix/http_server.hpp"
# include "connection_manager.hpp"
# include "node_manager.hpp"
# include "io_action_config.hpp"
# include "pin_list.hpp"
# include "global.hpp"

class ConnectionManager;

void regist_global_actions() {
    AsyncWebServer* server = ganix::http_server::get_server();

    server->on("/", HTTP_ANY, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", "hello!");
    });

    server->on("/nodes", HTTP_ANY, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", node_mgr.dump_json());
    });

    server->on("/config/list", HTTP_ANY, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", io_action_config.dump_string());
    });

    //json只需要设置本机，5s内会自动通过ACTION_CONFIG_SYNC同步出去
    ganix::http_server::on_json("/config/set", [](AsyncWebServerRequest *request, JsonVariant &json){
        int version = json[ARG_KEY_CONFIG_VERSION];
        JsonArray data = json[ARG_KEY_CONFIG_DATA];
        io_action_config.load_config_from_json_array(data, version);
        io_action_config.save_config_to_file();
        request->send(200, "text/plain", "success set config");
    });

    ganix::http_server::on_json("/config/append", [](AsyncWebServerRequest *request, JsonVariant &json){
        int version = json[ARG_KEY_CONFIG_VERSION];
        JsonArray data = json[ARG_KEY_CONFIG_DATA];
        for (auto line : data) {
            io_action_config.append_config(line.as<String>());
        }
        request->send(200, "text/plain", "success append config");
    });

    server->on("/output_pin_list", HTTP_ANY, [](AsyncWebServerRequest *request){
        std::vector<String> tmp(output_pin_list.size());
        //String tmp[output_pin_list.size()];
        for (int i=0; i < output_pin_list.size(); i++) {
            tmp[i] = output_pin_list[i]->get_name();
        }
         request->send(200, "text/plain", string_join(tmp, '\n'));
    });
}